﻿using CefSharp;
using CefSharp.Wpf;
using CommunityToolkit.Mvvm.Messaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Sockets;
using System.Runtime.ConstrainedExecution;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace HsServerHa.UserControls
{
    /// <summary>
    /// Syncthing.xaml 的交互逻辑
    /// </summary>
    public partial class Syncthing : System.Windows.Controls.UserControl
    {
        public Syncthing()
        {
            InitializeComponent();
            this.Loaded += Init;
            //this.SyncFile.Source = new Uri("http://127.0.0.1:8384");
            //this.SyncFile.Navigate(new Uri("http://127.0.0.1:8384"));
            //this.Dispatcher.BeginInvoke(new Action(() => {
            //    while (!this.SyncFile.IsLoaded)
            //    {
            //        this.loading.Visibility = Visibility.Visible;
            //        //Wait
            //    }

            //    this.loading.Visibility = Visibility.Hidden;
            //}));

            //this.SyncFile.Loaded += SyncFile_Loaded;
        }
        /// <summary>
        /// 校验同步文件接口是否开启
        /// </summary>
        /// <returns></returns>
        private bool CheckSyncFileAddress()
        {
            bool isCheck = true;
            string host = "127.0.0.1"; // 替换为你想要连接的主机地址
            int port = 8384; // 替换为你想要连接的端口号
            try
            {
                TcpClient client = new TcpClient(host, port);
                byte[] data = Encoding.ASCII.GetBytes("Hello, World!");
                NetworkStream stream = client.GetStream();
                stream.Write(data, 0, data.Length);
                byte[] response = new byte[1024];
                int bytesRead = stream.Read(response, 0, response.Length);
                string responseString = Encoding.ASCII.GetString(response, 0, bytesRead);
               
                stream.Close();
                client.Close();
            }
            catch (SocketException e)
            {
                isCheck = false;
            }
            return isCheck;
        }
        public static ChromiumWebBrowser cefWebBrowser = new ChromiumWebBrowser();
        /// <summary>
        /// 初始化加载
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="args"></param>
        private void Init(object obj, EventArgs args)
        {

            //if (!CheckSyncFileAddress())
            //{
            //    AduMessageBoxs.Show("同步文件接口未开启！");              
            //    return;
            //}
            try
            {
                if (!Cef.IsInitialized)
                {
                    CefSettings cefSettings = new CefSettings();
                    cefSettings.CefCommandLineArgs.Add("no-proxy-server", "1");
                    cefSettings.CefCommandLineArgs.Add("disable-gpu", "1");
                    cefSettings.CefCommandLineArgs.Add("proxy-server", "ProxyAddress");
                    cefSettings.CefCommandLineArgs.Add("disable-pinch", "1");
                    cefSettings.CefCommandLineArgs.Add("enable-media-stream", "1");
                    cefSettings.CefCommandLineArgs.Add("enable-system-flash", "1");
                    cefSettings.CefCommandLineArgs.Add("enable-speech-input", "1");
                    Cef.Initialize(cefSettings);

                }
                if (cefWebBrowser.Address != null)
                {
                    cefWebBrowser.Dispose();
                    cefWebBrowser = new ChromiumWebBrowser();
                }
                cefWebBrowser.JavascriptObjectRepository.Settings.LegacyBindingEnabled = true;
                cefWebBrowser.KeyboardHandler = new CEFKeyBoardHander();
                cefWebBrowser.Visibility = Visibility.Visible;
                cefWebBrowser.Load("http://127.0.0.1:8384");
                cefWebBrowser.FrameLoadEnd += new EventHandler<FrameLoadEndEventArgs>(this.CefWebBrowser_FrameLoadEnd);
                cefWebBrowserGrid.Children.Add(cefWebBrowser);//添加控件
            }
            catch { }
            

        }
        private void CefWebBrowser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
        {

        }
    }

    public class CEFKeyBoardHander : IKeyboardHandler
    {
        public bool OnKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey)
        {
            if (type == KeyType.KeyUp && Enum.IsDefined(typeof(Keys), windowsKeyCode))
            {
                var key = (Keys)windowsKeyCode;
                switch (key)
                {
                    case Keys.F12:
                        browser.ShowDevTools();
                        break;

                    case Keys.F5:

                        if (modifiers == CefEventFlags.ControlDown)
                        {
                            //MessageBox.Show("ctrl+f5");
                            browser.Reload(true); //强制忽略缓存

                        }
                        else
                        {
                            //MessageBox.Show("f5");
                            browser.Reload();
                        }
                        break;


                }
            }
            return false;
        }

        public bool OnPreKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey, ref bool isKeyboardShortcut)
        {
            return false;
        }
    }
}
